# -*- coding: utf-8 -*-
#魔方分割模块
##################################
import cv2 as cv

'''
for i in range(6):
	img=cv.imread("C:\\Users\\ASUS\\Desktop\\img\\big\\"+str(i)+".jpg");
	getBlocks(img);
	'''
#设置内缩像素
value=30;

#通过坐标获取图片的一个魔方块
#coord:x1,y2,x2,y2
def getBlockByCoord(img,coord):
	return img[coord[1]+value:coord[3]-value,coord[0]+value:coord[2]-value];

def splitByCoord(imgArray):
	#保存所有面的所有块
	blocks=[[],[],[],[],[],[]];
	#计算应该魔方块的长度
	blockLength=imgArray[0].shape[0]//3;
	for i in range(3):
		for j in range(3):
			#计算这个块的坐标
			x1=j*blockLength;
			y1=i*blockLength;
			x2=x1+blockLength;
			y2=y1+blockLength;
			coord=[x1,y1,x2,y2];
			#提取每一个面的对应坐标的块
			for k in range(len(imgArray)):
				blocks[k].append(getBlockByCoord(imgArray[k],coord));
	# 返回结果
	return blocks;


def sortByContourArea(contour):
	area=cv.contourArea(contour);
	return area;

def sortByY(rect):
	return rect[1];

def sortByX(rect):
	return rect[0];

#从一张图片中提取魔方块
def getBlocks(img):
	#canny
        #15,60 
	#minV=cv.getTrackbarPos("min","test");
	#maxV=cv.getTrackbarPos("max","test");
	#39,2
	canny=cv.Canny(img,50,37);
	#media=cv.medianBlur(canny,3);
	#cv.imshow("canny",canny);
	#cv.waitKey(0);
	#膨胀
	kernel = cv.getStructuringElement(cv.MORPH_RECT,(11,11));
	dilate = cv.dilate(canny,kernel);
	#cv.imshow("canny",dilate);
	#cv.waitKey(0);
	#反向二值化
	ret,binROI=cv.threshold(dilate,35,255,cv.THRESH_BINARY_INV);
	#提取轮廓
	hierarchy,contours,value=cv.findContours(binROI,cv.RETR_EXTERNAL,cv.CHAIN_APPROX_SIMPLE)    # 输出为三个参数  
	#绘制轮廓
	#cv.drawContours(img,contours,-1,(0,0,255),2);
	#cv.imshow("blocks",img);
	#cv.waitKey(10);
	#input("please:");
	#按照轮廓大小排序
	contours.sort(key=sortByContourArea);
	#提取目标框
	rects=[];
	length=len(contours);
	for i in range(9):
		rects.append(cv.boundingRect(contours[length-i-1]));
	#按照Y排序
	rects.sort(key=sortByY);
	#每行按照X开始排序
	blocks=[];
	rowRects=[];
	for i in range(9):
		rowRects.append(rects[i]);
		if (i+1)%3==0:
			rowRects.sort(key=sortByX);
			for rect in rowRects:
				x,y,w,h,=rect;
				block=img[y:y+h,x:x+w];
				block=cv.resize(block,(20,20));
				blocks.append(block);
			rowRects=[];
	#绘制所有blocks
	'''for rect in rects:
                x,y,w,h=rect;
                cv.rectangle(img, (x,y),(x+w,y+h), (0,0,255), 2);
                cv.imshow("blocks",img);
                cv.waitKey(0);'''
	return blocks;

'''
456258
for i in range(6):
    img3=cv.imread("/home/pi/Desktop/cube/test/big/"+str(i)+".jpg");
    getBlocks(img3);
    cv.waitKey(10);
    input("please:");'''

'''
cv.namedWindow("test");
def nothing(e):
    pass
cv.createTrackbar("min","test",20,200,nothing);
cv.createTrackbar("max","test",20,200,nothing);
while True:
    img3=cv.imread("C:/Users/ASUS/Desktop/test/big/4.jpg");
    getBlocks(img3);
    cv.waitKey(10);
'''
#通过识别来做
def splitByCanny(imgArray):
	blocks=[];
	for img in imgArray:
		blocks.append(getBlocks(img));
	return blocks;

#把所有图片全部分割提取出魔方块
def split(imgArray):
	return splitByCanny(imgArray);
